<template>
  <!-- 选择角色-->
  <a-modal :width="400" v-model:visible="showRoles" title="选择角色" title-align="start" ok-text="确认添加" :mask-closable="false" @cancel="closedDialog" @ok="submitAudit">
    <div class="dialog-con-w">
      <a-space style="margin-bottom: 10px">
        <a-input v-model="roleName" style="width: 300px" placeholder="" allow-clear />
        <a-button type="primary" @click="getRoleList">搜索</a-button>
      </a-space>
      <a-checkbox-group direction="vertical" v-model="checkedList" @change="handleChange">
        <a-checkbox v-for="(item, i) in roleList" :key="i" :value="item.id">{{ item.roleName }}</a-checkbox>
      </a-checkbox-group>
      <div style="margin-top: 20px">
        <a-checkbox :model-value="checkedAll" :indeterminate="indeterminate" @change="handleChangeAll">全选 </a-checkbox>
      </div>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue'
  import { findRoleListByParam } from '@/api/system'

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
  })

  const showRoles = ref(props.isShow)
  const roleName = ref()
  const checkedAll = ref(false)
  const indeterminate = ref(false)
  const roleList = ref<any>([]) //角色列表
  const checkedList = ref<any>([]) //角色列表

  // 获取角色列表
  async function getRoleList() {
    const res: any = await findRoleListByParam({ roleName: roleName.value })
    roleList.value = res?.data || []
  }
  getRoleList()

  function handleChangeAll(value: any) {
    indeterminate.value = false
    if (value) {
      checkedAll.value = true
      checkedList.value = roleList.value.map((el: any) => el.id)
    } else {
      checkedAll.value = false
      checkedList.value = []
    }
  }

  function handleChange(values: Array<any>) {
    if (values.length === roleList.value.length) {
      checkedAll.value = true
      indeterminate.value = false
    } else if (values.length === 0) {
      checkedAll.value = false
      indeterminate.value = false
    } else {
      checkedAll.value = false
      indeterminate.value = true
    }
  }

  // 确认
  async function submitAudit() {
    let list: Array<any> = []
    checkedList.value.forEach((id: string) => {
      let _data = roleList.value.find((el: any) => el.id == id)
      if (_data) {
        list.push({
          roleId: _data.id,
          roleName: _data.roleName,
          roleCode: _data.roleCode,
        })
      }
    })
    emit('success', list)
    closedDialog()
  }
  // 关闭
  function closedDialog() {
    showRoles.value = false
    emit('closed')
  }
</script>
<style lang="less" scoped>
  .dialog-con-w {
    max-height: calc(84vh - 100px);
    overflow-y: auto;
  }
</style>
